package day03;

import com.blackhorse.domain.Account;
import com.blackhorse.domain.Role;
import com.blackhorse.domain.User;
import com.blackhorse.xml.dao.RoleMapper;
import com.blackhorse.xml.dao.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class Demo3_ManyToMany {
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;
    private RoleMapper roleMapper;
    private UserMapper userMapper;

    @Before
    public void init() {
        try {
            InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = builder.build(in);
            sqlSession = sqlSessionFactory.openSession();
            roleMapper = sqlSession.getMapper(RoleMapper.class);
            userMapper = sqlSession.getMapper(UserMapper.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @After
    public void destory() {
        sqlSession.commit();
        if (sqlSession != null) {
            sqlSession.close();
        }
    }

    //查询所有角色
    @Test
    public void testFindAll() {
        List<Role> roles = roleMapper.findAll();
        for (Role role : roles) {
            System.out.println(role);
        }
    }

    //查询所有角色，同时多对多关联查询用户（使用Role包装User对象方式）
    @Test
    public void testFindAllRoleWithUsers() {
        List<Role> roles = roleMapper.findAllwithUsers();
        for (Role role : roles) {
            System.out.println("----------------------------------------");
            System.out.println(role);
            List<User> users = role.getUsers();
            if (users == null || users.size() == 0) {
                System.out.println("\tUser = null");
                continue;
            }
            for (User user : users) {
                System.out.println("\t" + user);
            }
        }
    }

    //查询所有用户，同时多对多关联查询角色（使用User包装Role对象方式）
    @Test
    public void testFindAllUserWithRoles() {
        List<User> users = userMapper.findAllwithRoles();
        //如果不显示Role则说明该用户没有角色，即user.getRoles().size()==0
        for (User user : users) {
            System.out.println("----------------------------------------");
            System.out.println(user);
            List<Role> roles = user.getRoles();
            if (roles == null || roles.size() == 0) {
                System.out.println("\tRole = null");
                continue;
            }
            for (Role role : roles) {
                System.out.println("\t" + role);
            }
        }
    }
}
